package cn.iocoder.yudao.module.system.service.gugu;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.QsRankingInfo;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.QsRankingQueryReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.QsRankingPageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.gugu.QsRankingDO;
import cn.iocoder.yudao.module.system.dal.mysql.gugu.QsRankingMapper;
import cn.iocoder.yudao.module.system.util.gugu.GuGuDataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 全球QS世界大学排名数据 Service 实现类
 */
@Service
@Slf4j
public class QsRankingServiceImpl implements QsRankingService {

    @Resource
    private QsRankingMapper qsRankingMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveQsRankingList(List<QsRankingInfo> qsRankingList) {
        if (qsRankingList == null || qsRankingList.isEmpty()) {
            return 0;
        }

        int savedCount = 0;
        for (QsRankingInfo info : qsRankingList) {
            // 检查是否已存在相同的记录
            boolean exists = existsQsRanking(info.getId());
            
            if (!exists) {
                QsRankingDO qsRanking = QsRankingDO.builder()
                        .universityId(info.getId())
                        .universityName(info.getUniversityName())
                        .region(info.getRegion())
                        .country(info.getCountry())
                        .city(info.getCity())
                        .logoUrl(info.getLogoUrl())
                        .rank(info.getRank())
                        .academicReputationRank(info.getAcademicReputationRank())
                        .academicReputationScore(info.getAcademicReputationScore())
                        .citationsPerFacultyRank(info.getCitationsPerFacultyRank())
                        .citationsPerFacultyScore(info.getCitationsPerFacultyScore())
                        .facultyStudentRatioRank(info.getFacultyStudentRatioRank())
                        .facultyStudentRatioScore(info.getFacultyStudentRatioScore())
                        .employerReputationRank(info.getEmployerReputationRank())
                        .employerReputationScore(info.getEmployerReputationScore())
                        .employmentOutcomesRank(info.getEmploymentOutcomesRank())
                        .employmentOutcomesScore(info.getEmploymentOutcomesScore())
                        .internationalStudentRatioRank(info.getInternationalStudentRatioRank())
                        .internationalStudentRatioScore(info.getInternationalStudentRatioScore())
                        .internationalResearchNetworkRank(info.getInternationalResearchNetworkRank())
                        .internationalResearchNetworkScore(info.getInternationalResearchNetworkScore())
                        .internationalFacultyRatioRank(info.getInternationalFacultyRatioRank())
                        .internationalFacultyRatioScore(info.getInternationalFacultyRatioScore())
                        .sustainabilityRank(info.getSustainabilityRank())
                        .sustainabilityScore(info.getSustainabilityScore())
                        .build();
                
                qsRankingMapper.insert(qsRanking);
                savedCount++;
            } else {
                log.debug("QS排名数据已存在，跳过保存: 大学ID={}, 大学名称={}", 
                        info.getId(), info.getUniversityName());
            }
        }

        return savedCount;
    }

    @Override
    public List<QsRankingDO> getQsRankingByUniversityName(String universityName) {
        return qsRankingMapper.selectByUniversityName(universityName);
    }

    @Override
    public List<QsRankingDO> getQsRankingByCountry(String country) {
        return qsRankingMapper.selectByCountry(country);
    }

    @Override
    public List<QsRankingDO> getQsRankingByRegion(String region) {
        return qsRankingMapper.selectByRegion(region);
    }

    @Override
    public List<QsRankingDO> getQsRankingByRankRange(Integer minRank, Integer maxRank) {
        return qsRankingMapper.selectByRankRange(minRank, maxRank);
    }

    @Override
    public QsRankingDO getQsRankingByUniversityId(String universityId) {
        return qsRankingMapper.selectByUniversityId(universityId);
    }

    @Override
    public PageResult<QsRankingDO> getQsRankingPage(QsRankingPageReqVO reqVO) {
        return qsRankingMapper.selectPage(reqVO);
    }

    @Override
    public boolean existsQsRanking(String universityId) {
        return qsRankingMapper.existsByUniversityId(universityId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> fetchAndSaveQsRanking(String appkey, String name, Integer pageindex, Integer pagesize) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证API Key
            if (!GuGuDataUtils.validateQsRankingApiKey(appkey)) {
                result.put("success", false);
                result.put("message", "无效的API Key");
                return result;
            }

            // 构建查询参数
            QsRankingQueryReqVO reqVO = new QsRankingQueryReqVO();
            reqVO.setName(name);
            reqVO.setPageindex(pageindex != null ? pageindex : 1);
            reqVO.setPagesize(pagesize != null ? pagesize : 10);

            // 调用API获取数据
            Map<String, Object> apiResult = GuGuDataUtils.getQsRankingInfo(reqVO);

            if (!Boolean.TRUE.equals(apiResult.get("success"))) {
                result.put("success", false);
                result.put("message", "API调用失败: " + apiResult.get("message"));
                return result;
            }

            @SuppressWarnings("unchecked")
            List<QsRankingInfo> qsRankingList = (List<QsRankingInfo>) apiResult.get("qsRankingList");

            if (qsRankingList == null || qsRankingList.isEmpty()) {
                result.put("success", true);
                result.put("message", "未获取到数据");
                result.put("savedCount", 0);
                result.put("totalCount", 0);
                result.put("apiTotalCount", apiResult.get("totalCount"));
                return result;
            }

            // 保存到数据库
            int savedCount = saveQsRankingList(qsRankingList);

            result.put("success", true);
            result.put("message", "成功获取并保存QS排名数据");
            result.put("savedCount", savedCount);
            result.put("totalCount", qsRankingList.size());
            result.put("apiTotalCount", apiResult.get("totalCount"));

            return result;
        } catch (Exception e) {
            log.error("获取并保存QS排名数据失败", e);
            result.put("success", false);
            result.put("message", "获取并保存QS排名数据失败: " + e.getMessage());
            return result;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteQsRankingByUniversityId(String universityId) {
        return qsRankingMapper.deleteByUniversityId(universityId);
    }

    @Override
    public List<QsRankingDO> getTopNUniversities(Integer topN) {
        return qsRankingMapper.selectTopN(topN);
    }

    @Override
    public List<QsRankingDO> getChineseUniversities() {
        return qsRankingMapper.selectChineseUniversities();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createQsRanking(QsRankingDO createReqVO) {
        qsRankingMapper.insert(createReqVO);
        return createReqVO.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateQsRanking(QsRankingDO updateReqVO) {
        qsRankingMapper.updateById(updateReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQsRanking(Long id) {
        qsRankingMapper.deleteById(id);
    }

    @Override
    public QsRankingDO getQsRanking(Long id) {
        return qsRankingMapper.selectById(id);
    }
}
